package com.wnxy.sk.product.job;

import com.wnxy.sk.product.constant.PromotionStatus;
import com.wnxy.sk.product.constant.RedisConstant;
import com.wnxy.sk.product.service.IPromotionSeckillService;
import com.wnxy.sk.product.vo.PromotionProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时执行的任务类
 */
@Component
public class PromotionJob {

    @Autowired
    private IPromotionSeckillService promotionSeckillService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 数据预热，加载秒杀活动列表
     */
    @Scheduled(cron = "0/15 * * 1 * ?")
    public void executeQuerySeckill() {
        //1. 查询秒杀时间已到，活动未开始的秒杀数据集合
        List<PromotionProductVo> voList =
                promotionSeckillService.findPromotionSeckill(PromotionStatus.UN_START);

        //2. 判断
        if (!CollectionUtils.isEmpty(voList)) {
            // 3. 秒杀活动列表数据不为空，把查询到的数据放入Redis缓存
            // Redis数据类型？ string、hash、list、set、zset ---> 列表，有序，list
            redisTemplate.opsForList().leftPushAll(RedisConstant.PRODUCT_SECKILL,voList);

            /* 初始化秒杀活动库存 */
            initStore(voList);

            // 4. 修改秒杀活动状态，从0-未开始改为1-进行中
            List<Integer> promotionIds = voList.stream()
                    .map(PromotionProductVo::getPromotionId)
                    .collect(Collectors.toList());
            promotionSeckillService.updateStatusByIds(promotionIds);
        }

    }

    /**
     * 初始化秒杀活动库存
     */
    private void initStore(List<PromotionProductVo> voList) {
        voList.forEach(vo->{
            // 秒杀活动id
            Integer promotionId = vo.getPromotionId();
            // 商品id
            Integer productId = vo.getProductId();
            // 秒杀活动库存数量
            Long count = vo.getCount();
            for (int i = 0; i < count; i++) {
                redisTemplate.opsForList().leftPush(
                        RedisConstant.SECKILL_COUNT+promotionId,productId);
            }
        });
    }
}
